
//  ZComposeViewController.swift
//  swift-weibo
//
//  Created by zero on 17/3/28.
//  Copyright © 2017年 zero. All rights reserved.
//

import UIKit

class ZComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        //  布局
        setupUI()
    }

    private func setupUI(){
        
        view.backgroundColor = UIColor.white
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", imageName: "", target: self, action: #selector(back))
        //  添加右侧按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBtn)
        
        navigationItem.rightBarButtonItem?.isEnabled = false
        
        
        //  设置头
        navigationItem.titleView = labTitleView
        
        //  注册通知监听键盘的活动
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoradNotifation), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        //  注册添加表情的通知
        NotificationCenter.default.addObserver(self, selector: #selector(addEmoji), name: NSNotification.Name(rawValue: EMOJINOTIFI), object: nil)
        
        //  删除按钮的通知
        NotificationCenter.default.addObserver(self, selector: #selector(deleteEmoji), name: NSNotification.Name(rawValue: DELETEBTNCLICK), object: nil)
        
        //  添加textView
        view.addSubview(composeTextView)
        
        //  约束 
        composeTextView.snp.makeConstraints { (make) in
            
            make.edges.equalTo(self.view)
        }
        
        //  添加底部view
        view.addSubview(bottomView)
        
        //  解除抢引用
        bottomView.btnClick = {[weak self](type) -> () in
            
            switch type {
            case .picture:
            
                //  调用方法
                self?.getImageFromPickerVC()
            case .camera:
                
                print("相机")
                
            case .emoticon:
                
                self?.changeTextViewInputView()
                
            case .mention:
                
                print("@")
                
            case .add:
                
                print("加号➕")
            
            }
            
        }
        //  约束
        bottomView.snp.makeConstraints { (make) in
            
            make.leading.bottom.trailing.equalTo(self.view)
            make.height.equalTo(40)
        }
        
        //  添加
        view.addSubview(pickerCollection)
        
        //  约束
        pickerCollection.snp.makeConstraints { (make) in
            
            make.centerX.equalTo(view)
            make.top.equalTo(view).offset(100)
            
        }
        
        pickerCollection.addPicture = {[weak self] ()->()in
            
            self?.getImageFromPickerVC()
        }
        
    }
    
    //  懒加载右侧按钮
    private lazy var rightBtn:UIButton = {
       
        let btn = UIButton()
        
        btn.setTitle("发送", for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        btn.setTitleColor(UIColor.darkGray, for: .disabled)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.setTitleColor(UIColor.white, for: .highlighted)
        btn.setBackgroundImage(UIImage(named:"common_button_white_disable"), for: .disabled)
        btn.setBackgroundImage(UIImage(named:"common_button_orange"), for: .normal)
        btn.setBackgroundImage(UIImage(named:"common_button_orange_highlighted"), for: .highlighted)
        
        btn.bounds = CGRect(x: 0, y: 0, width: 50, height: 30)

        btn.addTarget(self, action: #selector(sendWeibo), for: .touchUpInside)
        
        return btn
    }()
    
    
    //  发送微博
    @objc fileprivate func sendWeibo(){
        
        var allText = ""
        
        composeTextView.attributedText.enumerateAttributes(in: NSRange(location: 0, length: composeTextView.attributedText.length), options: []) { (dict, range, _) in
            
            
            if let att = dict["NSAttachment"] as? ZTextAttachment {
                // 字符串的拼接
                allText += att.emojiModel?.chs ?? " "
            }else{
                allText += composeTextView.attributedText.attributedSubstring(from: range).string
            }
            
        }
        
        pickerCollection.imgList.count > 0 ? uploadWeibo(statuses: allText) : updateWeibo(statuses: allText)
    }
    
    //  创建textView
    
    fileprivate lazy var composeTextView:ZCompaseTextView = {
       
        let view = ZCompaseTextView()
        
        view.delegate = self
        view.alwaysBounceVertical = true
        view.placeholder = "占位文字"
        view.font = UIFont.systemFont(ofSize: 14)
        
        return view
    }()
    
    //  创建titleView
    private lazy var labTitleView:UILabel = {
       
        let lab = UILabel()
        
        
        let name = "阿拉就叫狗蛋"
        let textString = "发布" + "\n" + name
        
        let attrStr = NSMutableAttributedString(string: textString)
        
        let range = (textString as NSString).range(of: name)
        
        attrStr.addAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 10),NSForegroundColorAttributeName:UIColor.orange], range: range)
        lab.textAlignment = .center
        
        lab.numberOfLines = 0
        
        lab.attributedText = attrStr
        lab.sizeToFit()
        
        return lab
    }()
    
    //  创建底部约束
    fileprivate lazy var bottomView:ZCompaseBottom = ZCompaseBottom()
    
    //  图片
    fileprivate lazy var pickerCollection:ZPickerCollection = ZPickerCollection()
    
    //  稀构函数
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

}
//MARK: 网路请求
extension ZComposeViewController{
    
    //  发送文字微博
    fileprivate func updateWeibo(statuses:String){
        
        ZNetworkTools.shared.update(statuses: statuses) { (res, error) in
            
            if error != nil{
                
                print("发送失败")
                
                return
            }
            
            //
            print("发布成功")
            
            self.dismiss(animated: true, completion: nil)
        }

    }
    
    //  发送图文微博
    fileprivate func uploadWeibo(statuses:String){
        
        ZNetworkTools.shared.upload(statuses: statuses, imageList: pickerCollection.imgList) { (res, error) in
            
            if error != nil{
                
                print("发送失败")
                
                return
            }
            
            print("发布成功")
            
            self.dismiss(animated: true, completion: nil)

        }
    }
    
}


//MARK:
extension ZComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    fileprivate func getImageFromPickerVC(){
        
        let pickerVC = UIImagePickerController()
        
        pickerVC.delegate = self
        
        present(pickerVC, animated: true, completion: nil)
        
    }
    
    //  代理方法
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        
        picker.dismiss(animated: true, completion: nil)
        
        guard let image = info["UIImagePickerControllerOriginalImage"] as? UIImage else {
            
            print("Pikcer获取图片失败")
            return
        }
        
        pickerCollection.addImage(image: image.cutImage(maxWeight: 400))
        
        
    }
}

////MARK:渲染图片
extension ZComposeViewController{
    
    fileprivate func cutImage(image:UIImage,maxWeight:CGFloat) -> UIImage{
        
        
        if image.size.width < maxWeight {
            
            return image
        }
        
        //  计算高度
        let maxHeight = maxWeight / image.size.width * image.size.height
        
        //  得到大小
        let imageRect = CGRect(x: 0, y: 0, width: maxWeight, height: maxHeight)
        
        //  开启上下文
        UIGraphicsBeginImageContext(imageRect.size)
        
        //  把图片渲染到上下问中
        image.draw(in: imageRect)
        
        //  从上下文中获取图片
        let targetImage = UIGraphicsGetImageFromCurrentImageContext()
        //  关闭上下文
        UIGraphicsEndImageContext()
        
        return targetImage!
    }
}

//MARK:键盘
extension ZComposeViewController{
    
    @objc fileprivate func keyBoradNotifation(noti:Notification){

        
        guard let keyInfo = noti.userInfo else {
            
            return
        }
        
        guard let endUser = keyInfo["UIKeyboardFrameEndUserInfoKey"] else {
            
            return
        }
        
        let rect = (endUser as! NSValue) .cgRectValue
        
        //  获取时长
        let duration = (keyInfo["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber).doubleValue
        
        let offset = rect.origin.y - UIScreen.main.bounds.size.height
        
        self.bottomView.snp.updateConstraints { (make) in
            
            make.bottom.equalTo(self.view).offset(offset)
        }        //  动画
        UIView.animate(withDuration: duration) {
            
    
            //  刷新
            self.view.layoutIfNeeded()
        }
    }
    
    
    @objc fileprivate func addEmoji(noti:Notification){
        
        //  获取点击的按钮的模型
        guard let model = noti.object as? ZEmoticonModel else {
            
            print("亲!表情按钮的模型转换的时候出错了")
            
            return
        }
        
        
        //  保存按钮到最近的数组中
        ZBundleTools.share.saveEmoji(emojiModel: model)
        
        
        //  判断是否是emoji表情
        if model.type == "1" {
            
            composeTextView.insertText(model.code?.emoji() ?? "")
            
        }else{
            
            //  创建可变的富文本
            let mutableAttributedString = NSMutableAttributedString(attributedString: composeTextView.attributedText)
            
            //  获取行高
            let lineH = composeTextView.font?.lineHeight
            //  图片
            let image = UIImage(named: model.allPath!, in: ZBundleTools.share.getPath(), compatibleWith: nil)
        
            //  获取光标位置
            let selectIndex = composeTextView.selectedRange
            
            //  富文本附件
            let textAttachment = ZTextAttachment()
            
            //  记录模型数据
            textAttachment.emojiModel = model
            
            textAttachment.image = image
            
            //  设置富文本附件的
            textAttachment.bounds = CGRect(x: 0, y: -2, width: lineH!, height: lineH!)
            
            //  根据富文本空间来创建富文本
            let attributedString = NSAttributedString(attachment: textAttachment)
            
            //  添加到可变的富文本中
//            mutableAttributedString.append(attributedString)
            mutableAttributedString.replaceCharacters(in: selectIndex, with: attributedString)
            
            mutableAttributedString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 14), range: NSRange(location: 0, length: mutableAttributedString.length))
            
            //  赋值
            composeTextView.attributedText = mutableAttributedString
            
            
            //  修改光标的位置
            composeTextView.selectedRange = NSRange(location: selectIndex.location + 1, length: 0)
            
            //  手动调代理方法 发送通知
            
            NotificationCenter.default.post(name: NSNotification.Name.UITextViewTextDidChange, object: nil)
            composeTextView.delegate?.textViewDidChange!(composeTextView)
            
            
        }
        
    }
    
    @objc fileprivate func deleteEmoji(){
        
        composeTextView.deleteBackward()
    }
}
//MARK:代理
extension ZComposeViewController:UITextViewDelegate{
    
    func textViewDidChange(_ textView: UITextView) {
        
        //  按钮点击
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        scrollView.resignFirstResponder()
    }
}


//  左侧返回按钮
extension ZComposeViewController{
    
    @objc func back(){
        
        self.dismiss(animated: true, completion: nil)
    }
}

//  emoji
extension ZComposeViewController{
    
    fileprivate func changeTextViewInputView(){
        

        composeTextView.becomeFirstResponder()
        
        //  切换键盘
        composeTextView.inputView = composeTextView.inputView == nil ? ZEmoticonKeyBoardView() : nil
        
        bottomView.isEmoji = !(composeTextView.inputView == nil)
        
        composeTextView.reloadInputViews()
        

    }
}
